//
//  WTOAuthViewController.swift
//  WTSinaWeibo
//
//  Created by  Wellim on 16/6/25.
//  Copyright © 2016年  Wellim. All rights reserved.
//

import UIKit
import SVProgressHUD

class WTOAuthViewController: UIViewController {

    
    override func loadView() {
        
        view = webview
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        
       view.backgroundColor = UIColor.whiteColor()
        setUpNav()
        
        
        
    }
    
    
    // MARK: - 设置导航栏
    
    /**
     设置导航栏
     */
    func setUpNav(){
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(WTOAuthViewController.cancelClick))
    
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFillClick")
    
        navigationItem.title = "OAuth登录"
    }
    
    // MARK: - 监听事件
    //取消
  @objc  private func cancelClick(){
    
    
      dismissViewControllerAnimated(true, completion: nil)
    
    }
   
    //自动填充
    @objc private func autoFillClick(){
    
        let jsStirng = "document.getElementById('userId').value='tj520lw@163.com',document.getElementById('passwd').value='wellim1986'"
        
        webview.stringByEvaluatingJavaScriptFromString(jsStirng)

       
    
    
    }
    
    // MARK: - 懒加载控件UIWebView
    
    
    lazy var webview :UIWebView = {
    
    let webView = UIWebView()
    
     webView.delegate = self
        
    let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(Redirect_URI)")
        
        
        let requeset = NSURLRequest(URL: url!)
        
        webView.loadRequest(requeset)
        
    
        return webView
    }()
    

}


// MARK: - UIWebViewDelegate代理
extension WTOAuthViewController:UIWebViewDelegate{
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    //加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
       
        SVProgressHUD.dismiss()
    }
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
        if error?.code == 102 {
            SVProgressHUD.dismiss()
        } else {
            SVProgressHUD.showInfoWithStatus("您的网络不给力")
        }
    }
    
    // webView将要加载request
    // 如果返回true 代表 继续加载
    // 如果返回false  代表停止加载
    // 默认不实现 代表true
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL?.absoluteString
        // 判断urlString 是否有值 而且 他的前缀是我们的回调页
     
        if let u = urlString where u.hasPrefix(Redirect_URI){
        // 请求参数键值对
            let query = request.URL?.query
            // 可选值判断
            if let q = query {
               // 字符串截取获得code
                let code = q.substringFromIndex("code=".endIndex)
                
                print("终于等到你还好没放弃：\(code)")
                
                loadUserAccount(code)
                
                 // 如果我们已经拿到code 就没必要继续加载
                  return false
                
            }
            
        }
        
        return true
    }

    
}


extension WTOAuthViewController{

    func loadUserAccount(code:String){
    
    WTNetworktools.sharedNetworktools.oauthLoadUserAccount(code, success: { (resposnse) in
        // 判断请求回来的res 是否有值 而且 是否可以转成一个字典
        // 如果在在判断可选值是否有值 可以转成你想要的类型 一般情况下 as?
//        print(resposnse)
     guard let res = resposnse as? [String :AnyObject] else{
        
        print("返回的数据不是一个字典")
            
            return
        }
        // 字典转模型
        let userAccount = WTUserAccount(dict: res)
        
       //调下面的方法传值
        self.loadUserInfo(userAccount)
       
        }) { (error) in
            
            
            print(error)
            
        }
        
        
    }

    func loadUserInfo(userAccount:WTUserAccount)  {
        
        WTNetworktools.sharedNetworktools.oauthLoadUserInfo(userAccount, success: { (resposnse) in
        // 判断是否有值而且可以转成字典
         guard let res = resposnse as? [String:AnyObject] else{
            
            return
            
            }
           userAccount.screen_name = res["screen_name"] as? String
            
           userAccount.avatar_large = res["avatar_large"] as? String
             // 通过归档保存数据
            WTUserAccountTools.sharedUserAccountTools.saveUserAccount(userAccount)
          
            self.dismissViewControllerAnimated(false, completion: { 
                
                // 发送通知告知appdelegate 切换跟控制器 rootVc = welcomeVc
                NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVCNoti, object: nil)
                
                SVProgressHUD.dismiss()

            })
            
            
            
            
            }) { (error) in
                
               print("失败\(error)")
        }
        
        
    }



}